package socket;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author huyong
 * @version 1.0.0
 * @description
 * @date 2015/5/26 14:30
 */
public class Server {

	public static void main(String[] args) throws Exception{
		ServerSocket serverSocket = new ServerSocket(9999);
		Socket socket = serverSocket.accept();
		InputStream is = socket.getInputStream();
		OutputStream os = socket.getOutputStream();

		while (true) {
			byte[] header = new byte[2];
			int count = is.read(header);
			//System.out.println("header length is:" + count);
			String xml;
			if(new String(header, "UTF-8").equals("00")) {
				byte[] body = new byte[6];
				is.read(body);
				System.out.println("package_request: " + new String(body, "UTF-8"));
				xml = "package_response:" + System.currentTimeMillis();
			}else{
				int bodyLen = Integer.parseInt(new String(header, "UTF-8"));
				byte[] body = new byte[bodyLen];
				is.read(body);
				System.out.println(new String(body, "UTF-8"));
				xml = "client_response:" + System.currentTimeMillis();
			}
			os.write((xml.length() + xml).getBytes("UTF-8"));
			os.flush();
		}
	}
}
